<template>
    <el-dialog 
        :visible.sync="visible" 
        title="添加管理员" 
        width="500px" 
        :before-close="handleClose"
        center 
    >
        <el-form 
            ref="form" 
            :model="form" 
            :rules="rules" 
            label-width="100px" 
            label-position="left"
            class="manager-form"  
        >
            <!-- 增设方式选择 -->
            <el-form-item 
                label="增设方式" 
                prop="employeeCreatedSelect"
                class="form-item"
            >
                <el-select 
                    v-model="form.employeeCreatedSelect" 
                    placeholder="请选择增设员工的方式"
                    @change="handleCreateModeChange"
                    clearable
                    style="width: 100%;" 
                >
                    <el-option label="已在其他端注册" value="0"></el-option>
                    <el-option label="新建账号" value="1"></el-option>
                </el-select>
            </el-form-item>

            <!-- 手机号输入 -->
            <el-form-item 
                label="手机号" 
                prop="phone"
                class="form-item"
            >
                <el-input 
                    v-model="form.phone" 
                    placeholder="请输入手机号" 
                    clearable
                    style="width: 100%;"
                ></el-input>
            </el-form-item>

            <!-- 密码框：动态渲染 -->
            <el-form-item 
                label="密码" 
                prop="password" 
                v-if="form.employeeCreatedSelect === '1'" 
                :rules="passwordRules"
                class="form-item"
            >
                <el-input 
                    v-model.trim="form.password" 
                    type="password" 
                    placeholder="请输入密码（至少4位）" 
                    @input="handlePasswordInput"
                    clearable
                    style="width: 100%;"
                ></el-input>
            </el-form-item>

            <!-- 管理员类型选择 -->
            <el-form-item 
                label="管理员类型" 
                prop="type"
                class="form-item"
            >
                <el-select 
                    v-model="form.type" 
                    placeholder="请选择管理员类型"
                    clearable
                    style="width: 100%;"
                >
                    <el-option label="普通管理员" value="NORMAL"></el-option>
                    <el-option label="超级管理员" value="SUPER"></el-option>
                </el-select>
            </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
            <el-button @click="handleClose" class="cancel-btn">取消</el-button>
            <el-button type="primary" @click="submitForm" class="confirm-btn">确定</el-button>
        </div>
    </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex';
import { createEmployee } from '@/util/manager_api/manager';
import { Message } from 'element-ui';

export default {
    name: 'AddManagerDialog',
    props: {
        visible: {
            type: Boolean,
            default: false
        }
    },
    computed: {
        ...mapGetters('manager', ['isSuperAdmin']),
        shouldShowPassword() {
            return this.form.employeeCreatedSelect === '1';
        },
        passwordRules() {
            return this.shouldShowPassword
                ? [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 4, message: '密码长度不能小于4位', trigger: 'blur' }
                ]
                : [];
        }
    },
    data() {
        return {
            form: {
                employeeCreatedSelect: null,
                phone: '',
                password: '',
                type: null
            },
            rules: {
                employeeCreatedSelect: [
                    { required: true, message: '请选择增设员工的方式', trigger: 'change' }
                ],
                phone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
                ],
                type: [
                    { required: true, message: '请选择管理员类型', trigger: 'change' }
                ]
            }
        };
    },
    watch: {
        visible(val) {
            if (!val) {
                this.$nextTick(() => {
                    this.resetFormFields();
                });
            }
        }
    },
    methods: {
        handleClose() {
            this.$emit('update:visible', false);
        },
        resetFormFields() {
            if (this.$refs.form) {
                this.$refs.form.clearValidate();
                this.$refs.form.resetFields();
                this.form = {
                    employeeCreatedSelect: null,
                    phone: '',
                    password: '',
                    type: null
                };
            }
        },
        handleCreateModeChange(val) {
            if (val === '0') {
                this.form.password = '';
            }
            if (this.$refs.form) {
                this.$refs.form.validateField('password');
            }
        },
        handlePasswordInput(val) {
            this.form.password = val.replace(/\s+/g, '');
        },
        submitForm() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.addManager();
                } else {
                    Message.error('表单验证失败，请检查输入');
                    return false;
                }
            });
        },
        async addManager() {
            try {
                const data = {
                    employeeCreatedSelect: this.form.employeeCreatedSelect,
                    phone: this.form.phone,
                    type: this.form.type
                };

                if (this.shouldShowPassword) {
                    data.password = this.form.password;
                }

                const response = await createEmployee(data);
                const resData = response.data || response;
                
                if (resData.code === 201) {
                    this.$store.commit('manager/SET_TOKEN', resData.data);
                    this.handleClose();
                    this.$emit('refreshUserList');
                    Message.success('添加管理员成功');
                } else {
                    Message.error(resData.message || '添加管理员失败');
                }
            } catch (error) {
                console.error('网络请求异常', error);
                Message.error('网络错误，请稍后重试');
            }
        }
    }
};
</script>
<style scoped>
/* 表单容器样式 */
.manager-form {
    padding: 25px;  /* 增加内边距，避免内容贴边 */
    background-color: #fff;
    border-radius: 4px;
}

/* 表单项样式 */
.form-item {
    margin-bottom: 18px;  /* 统一表单项间距 */
}

/* 底部按钮区域样式 */
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    padding: 15px 25px;  /* 调整底部边距，与表单内边距呼应 */
    border-top: 1px solid #ebeef5;
    background-color: #f5f7fa;  /* 底部区域灰色背景，区分表单区域 */
    border-radius: 0 0 4px 4px;  /* 与对话框圆角呼应 */
}

/* 按钮样式优化 */
.cancel-btn {
    margin-right: 10px;  /* 取消按钮与确定按钮间距 */
}

.confirm-btn {
    width: 100px;  /* 确定按钮固定宽度，更美观 */
}

/* 响应式调整（适配小屏幕） */
@media (max-width: 768px) {
    .manager-form {
        padding: 15px;
    }
    .dialog-footer {
        padding: 10px 15px;
        flex-direction: column;  /* 小屏幕按钮纵向排列 */
        gap: 10px;
    }
    .cancel-btn, .confirm-btn {
        width: 100%;
        margin-right: 0;
    }
}
</style>